<template>
  <div class="addgoods">
           <!--头部面包屑导航-->
         <el-breadcrumb separator-class="el-icon-arrow-right" >
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
             <!-- 提示区 --> 
            <el-alert title="添加商品信息" type="info" :closable="false" center show-icon></el-alert>
            <!-- 进度条 -->
            <el-steps :space="200" :active="activeindex-0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!-- tabs 区 -->
            <el-form :model="addruleForm" :rules="addrules" ref="addruleref" label-width="100px" label-position="top">
                <el-tabs v-model="activeindex" :tab-position="'left'" :before-leave="beforetabsleave" @tab-click="tabclick">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addruleForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price" >
                            <el-input v-model="addruleForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight" >
                            <el-input v-model="addruleForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number" >
                            <el-input v-model="addruleForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                                v-model="addruleForm.goods_cat"
                                :options="catelist"
                                :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children' }"
                                @change="handleChange">
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item :label="item.attr_name" v-for="(item) in manylist" :key="item.attr_id">
                            <el-checkbox-group v-model="item.attr_vals" >
                                <el-checkbox border v-for="(item1,i) in item.attr_vals" :key="i" :label="item1"></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item :label="item2.attr_name" v-for="(item2,i2) in onlylist" :key="i2">
                            <el-input v-model="item2.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload
                            :on-success="handlesuccess"
                            :headers="headerobj"
                            action="https://lianghj.top:8888/api/private/v1/upload"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            list-type="picture">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor v-model="addruleForm.goods_introduce"></quill-editor>
                        <el-button type="primary" class="btnadd" @click="add">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <!-- 预览图片 -->
        <el-dialog
            
            title="图片预览"
            :visible.sync="imgdialogVisible"
            width="30%"
            >   
            <img :src="preimg" alt="" class="preimg">  
        </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
    created() {
        this.getCatelist()     
    },
    data() {
        return {
            catelist:[],//下拉列表数据
            activeindex:'0',
            imgdialogVisible:false,
            headerobj:{
                Authorization:window.sessionStorage.getItem('token')
            },//图片上传时的请求头对象
            selectvalue:[],//下拉选择的数组
            preimg:'',
            manylist:[],//动态参数列表数据
            onlylist:[],//静态属性列表数据
            addruleForm:{
                goods_name:"",
                goods_price:0,
                goods_weight:0,
                goods_number:0,
                goods_cat:[],
                pics:[],//图片的数组
                goods_introduce:"",
                attrs:[]
            },
            addrules:{
                goods_name:[{ required: true, message: '请输入商品名称', trigger: 'blur' },
                            { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }],
                goods_price:[{ required: true, message: '请输入商品价格', trigger: 'blur' }],
                goods_weight:[{ required: true, message: '请输入商品重量', trigger: 'blur' }],
                goods_number:[{ required: true, message: '请输入商品数量', trigger: 'blur' }],
                goods_cat:[{ required: true, message: '请选择商品分类', trigger: 'blur' }],
            }
        }    
    },
    methods: {
        //获取商品分类数据
        async getCatelist()  {
            const {data:res} = await this.$http.get('categories',{params:{type:3}})
            if(res.meta.status!=200) return this.$message.error("获取下拉列表数据失败")
            this.catelist = res.data
        },
        //级联器选择变化函数
        handleChange(){
            console.log(this.addruleForm.goods_cat)
            if(this.addruleForm.goods_cat.length!=3){
                this.addruleForm.goods_cat=[]
            }
        },
        //标签页的切换
        beforetabsleave(activename,oldactivename){
            if(this.addruleForm.goods_cat.length!=3 && oldactivename==='0') {
                this.$message.info("请填写相关信息")
                return false
            }
            return true
        },
        //图片预览
        handlePreview(file){
            console.log(file)
            this.preimg = file.url
            this.imgdialogVisible = true
        },
        //添加
        add(){
            this.$refs.addruleref.validate(async valid=>{
                if(!valid) return this.$message.error("数据填写不规范")
                const form = _.cloneDeep(this.addruleForm)
                form.goods_cat =this.addruleForm.goods_cat.join(',')
                this.manylist.forEach(item=>{
                    const newinfo = {attr_id:item.attr_id,attr_value:item.attr_vals.join(' ') }
                    this.addruleForm.attrs.push(newinfo)
                })
                this.onlylist.forEach(item=>{
                    const newinfo = {attr_id:item.attr_id,attr_value:item.attr_vals }
                    this.addruleForm.attrs.push(newinfo)
                })
                
                form.attrs = this.addruleForm.attrs
                const {data:res} = await this.$http.post('goods',form)
                if(res.meta.status!=201) return this.$message.error("添加商品失败")
                this.$router.push('/goods')
                return this.$message.success("添加商品成功")

            })
        },
        //移除图片
        handleRemove(file){
            const filepath = file.response.data.tmp_path
            const i = this.addruleForm.pics.findIndex(item=>{
                item.pic == filepath
            })
            this.addruleForm.pics.splice(i,1)
        },
        //图片上传成功
        handlesuccess(response){
            console.log(response)
            const picInfo = {pic:response.data.tmp_path}
            this.addruleForm.pics.push(picInfo)
        },
        //tabs点击事件
        async tabclick(){
            console.log(this.activeindex)
            if(this.activeindex==='1') //证明访问的是动态参数面板
            {
                const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                    params:{sel:'many'}
                })
                if(res.meta.status!=200) return this.$message.error("获取动态参数数据失败")
                res.data.forEach(item=>{
                    item.attr_vals = item.attr_vals.length==0? []:item.attr_vals.split(' ')
                })
                this.manylist = res.data
            }else if(this.activeindex==='2')
            {
                const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                    params:{sel:'only'}
                })
                if(res.meta.status!=200) return this.$message.error("获取静态属性数据失败")
                this.onlylist = res.data
            }
        }
    },
    computed:{
        cateId(){
            if(this.addruleForm.goods_cat.length == 3){
                return this.addruleForm.goods_cat[2]
            }
            return null
        }
    }
}
</script>

<style scoped>
.el-steps{
    margin-top: 10px;
}
.el-step__title.is-process{
    font-size: 13px;
}
.el-tabs{
    margin-top: 10px;
}
.preimg{
    width: 100%;
}
.btnadd{
    margin-top: 10px;
}
</style>